/**
 * @project leadnews-project
 * @author MECHREVO
 * @date 2024/1/24 22:06:21
 * @version 1.0
 */
package com.heima.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.BehaviorEnums;
import com.heima.model.user.dtos.FollowDto;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.UserFollowService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements UserFollowService {

    @Autowired
    private CacheService cacheService;
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private ApUserRealnameMapper apUserRealnameMapper;

    /**
     * 用户关注的功能
     *
     * @param followDto
     * @return
     */
    @Override
    public ResponseResult userFollow(FollowDto followDto) {
        //1.先判断作者是否是实名认证
        String UserId = AppThreadLocalUtil.getUser().getId().toString();
        if (StringUtils.isEmpty(UserId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.如果不是就认为没有实名认证是游客无法关注
        //3如果认证成功，就存入redis中，并且粉丝数＋1
        String key = BehaviorEnums.USER_ID + UserId;
        String key2 = BehaviorEnums.AUTHOR_ID + followDto.getAuthorId();
        /*ApUser apUser = apUserMapper.selectById(UserId);
        //用户名称
        String name = apUser.getName();*/
        if (followDto.getOperation() == 0) {
            //redis中存的key是用户的IDvalue作者的Id是list
            cacheService.zAdd(key, JSON.toJSONString(followDto.getAuthorId()), System.currentTimeMillis());
            //redis中key是作者value是粉丝
            cacheService.zAdd(key2, JSON.toJSONString(UserId), System.currentTimeMillis());
        } else if (followDto.getOperation() == 1) {
            //取消关注就减少
            //4.取消关注。在redis中删除
            cacheService.zRemove(key, JSON.toJSONString(followDto.getAuthorId()));
            cacheService.zRemove(key2, JSON.toJSONString(UserId));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
